package com.swp.oa.sys.util;

import java.io.IOException;
import java.text.SimpleDateFormat;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.StdSerializerProvider;
import org.codehaus.jackson.type.TypeReference;


/**
 * Json实用类，扩展封装Jackson.
 * 
 * @author 刘奇
 * @since 2013
 * @version 1.0.0
 */
public class JsonUtils {
	    private static final Logger log = Logger.getLogger(JsonUtils.class);
	  
	    final static ObjectMapper objectMapper;
	 
	    /**
	     * 是否打印美观格式
	     */
	    static boolean isPretty = false;
	 
	    static {
	        StdSerializerProvider sp = new StdSerializerProvider();
	        
	        sp.setNullValueSerializer(new NullSerializer());
	        objectMapper = new ObjectMapper(null, sp, null);
	        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	    }
	 
	    public static ObjectMapper getObjectMapper() {
	        return objectMapper;
	    }
	    /**
	     * JSON串转换为Java泛型对象，可以是各种类型，此方法最为强大。用法看测试用例。
	     * @param <T>
	     * @param jsonString JSON字符串
	    * @param tr TypeReference,例如: new TypeReference< List<FamousUser> >(){}
	     * @return List对象列表
	     */
	    @SuppressWarnings("unchecked")
		public static <T> T json2GenericObject(String jsonString, TypeReference<T> tr) {
	 
	        if (jsonString == null || "".equals(jsonString)) {
	            return null;
	        } else {
	            try {
	                return (T) objectMapper.readValue(jsonString, tr);
	            } catch (Exception e) {
	            	e.printStackTrace();
	                log.warn("json error:" + e.getMessage());
	            }
	        }
	        return null;
	    }
	    /**
	     * JsonNode转换为Java泛型对象，可以是各种类型，此方法最为强大。用法看测试用例。
	     * 
	     * @param <T>
	     * @param node JsonNode
	     * @param tr TypeReference,例如: new TypeReference< List<FamousUser> >(){}
	     * @return List对象列表
	     */
	    public static <T> T jsonNode2GenericObject(JsonNode node, TypeReference<T> tr) {
	 
	        if (node == null || "".equals(node)) {
	            return null;
	        } else {
	            try {
	                return (T) objectMapper.readValue(node, tr);
	            } catch (Exception e) {
	                log.warn("json error:" + e.getMessage());
	            }
	        }
	        return null;
	    }
	    /**
	     * 根据json串和节点名返回节点
	     * 
	     * @param json
	     * @param nodeName
	     * @return
	     */
	    public static JsonNode getNode(String json, String nodeName) {
	        JsonNode node = null;
	        try {
	            node = JsonUtils.getObjectMapper().readTree(json);
	            return node.get(nodeName);
	        } catch (JsonProcessingException e) {
	            log.warn("json error:" + e.getMessage());
	        } catch (IOException e) {
	            log.warn("json error:" + e.getMessage());
	        }
	        return node;
	    }
	 
	    /**
	     * Java对象转Json字符串
	     * 
	     * @param object Java对象，可以是对象，数组，List,Map等
	     * @return json 字符串
	     */
	    public static String toJson(Object object) {
	        String jsonString = "";
	        try {
	            if (isPretty) {
	                jsonString = objectMapper.defaultPrettyPrintingWriter().writeValueAsString(object);
	            } else {
	                jsonString = objectMapper.writeValueAsString(object);
	            }
	        } catch (Exception e) {
	            log.warn("json error:" + e.getMessage());
	        }
	        return jsonString;
	 
	    }
	 
	    /**
	     * Json字符串转Java对象
	     * 
	     * @param jsonString
	     * @param c
	     * @return
	     */
	    public static Object json2Object(String jsonString, Class<?> c) {
	 
	        if (jsonString == null || "".equals(jsonString)) {
	            return "";
	        } else {
	            try {
	                return objectMapper.readValue(jsonString, c);
	            } catch (Exception e) {
	                log.warn("json error:" + e.getMessage());
	            }
	 
	        }
	        return "";
	    }

}

 class NullSerializer extends JsonSerializer<Object> {
	 
    public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jgen.writeString("");
    }
}  
